# -- coding: utf-8 --
# @time : 2023/4/21
# @author : 周梦泽
# @file : restock_cycle.py
# @software: pycharm


"""
补单周期表
"""
import numpy as np
import pandas as pd


def calculation_order(excel_path: str, day: int = 7) -> tuple[pd.DataFrame, list]:
    """
    1.计算每个关键词的补单数
    2.新增n个空列:n为补单周期 7或30
    :param excel_path: excel路径
    :param day: 补单周期可以选择7天或30天
    :return:返回data_df：未完善的补单周期表 和day_list补单周期列表
    """
    excel_data = pd.read_excel(excel_path, sheet_name="关键词+竞品词")
    data_df = excel_data.loc[:, ["关键词", "搜索人数"]]
    num_list = [(search_count // 10000) if (search_count // 10000) >= 1 else 1 for search_count in data_df['搜索人数']]
    # 检查商是否小于1，如果是，则将num设置为1。否则，它将num设置为商的整数部分
    if len(num_list) != len(data_df):
        # 如果补单数计算错误，则抛出异常
        raise ValueError("补单数计算错误")
    data_df.drop(columns=["搜索人数"], inplace=True)
    data_df["补单数"] = num_list
    # 新增n个空列:n为补单周期 7或30
    day_list = [f"第{i}天" for i in range(1, day + 1)]
    data_df[day_list] = 0
    return data_df, day_list


def order_date(excel_path: str, day: int = 7) -> pd.DataFrame:
    """
    计算每个关键词的补单日期分布
    :param excel_path: excel路径
    :param day: 补单周期可以选择7天或30天
    :return: 返回data_df：补单周期表
    """
    data_df, day_list = calculation_order(excel_path, day)
    # 将补单数平均分配到周一至周日
    for index, row in data_df.iterrows():
        daily_count, remainder = divmod(row['补单数'], day)
        data_df.loc[index, day_list] = daily_count
        # 将剩余的部分分配到前几天
        for i in range(day + 1):
            if remainder == 0:
                break
            if data_df.iloc[:, 1 + i].sum() < data_df['补单数'].sum() / day:
                data_df.at[index, data_df.columns[1 + i]] += 1
                remainder -= 1
    data_df = data_df.replace(0, np.nan)

    with pd.ExcelWriter(excel_path, engine='openpyxl', mode='a') as writer:
        data_df.to_excel(writer, sheet_name='补单周期', index=False)

    return data_df

